import {
  Card,
  Table,
  Tree,
  Row,
  Col,
  Button,
  Modal,
  Form,
  Input,
  message,
  Transfer,
} from "antd"
import { useState, useEffect } from "react"
import PageHeaderWrapper from "@/components/pageHeaderWrapper"
import "./index.less"

function Permission() {
  const [roles, setRoles] = useState([])
  const [permissions, setPermissions] = useState([])
  const [selectedRole, setSelectedRole] = useState(null)
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [form] = Form.useForm()

  // 角色表格列定义
  const columns = [
    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
    },
    {
      title: "角色描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <div>
          <Button type="link" onClick={() => handleEditRole(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleConfigPermissions(record)}>
            配置权限
          </Button>
          <Button type="link" danger onClick={() => handleDeleteRole(record)}>
            删除
          </Button>
        </div>
      ),
    },
  ]

  // 模拟获取角色列表
  const fetchRoles = async () => {
    setLoading(true)
    try {
      // 替换为实际API调用
      const response = await fetch("/api/roles")
      const data = await response.json()
      setRoles(data)
    } catch (error) {
      message.error("获取角色列表失败")
    } finally {
      setLoading(false)
    }
  }

  // 模拟权限树数据
  const permissionTreeData = [
    {
      title: "系统管理",
      key: "system",
      children: [
        {
          title: "用户管理",
          key: "user",
          children: [
            { title: "查看用户", key: "user:view" },
            { title: "创建用户", key: "user:create" },
            { title: "编辑用户", key: "user:edit" },
            { title: "删除用户", key: "user:delete" },
          ],
        },
        {
          title: "角色管理",
          key: "role",
          children: [
            { title: "查看角色", key: "role:view" },
            { title: "创建角色", key: "role:create" },
            { title: "编辑角色", key: "role:edit" },
            { title: "删除角色", key: "role:delete" },
          ],
        },
      ],
    },
  ]

  // 处理角色相关操作
  const handleAddRole = () => {
    form.resetFields()
    setModalVisible(true)
  }

  const handleEditRole = (role) => {
    form.setFieldsValue(role)
    setModalVisible(true)
  }

  const handleDeleteRole = async (role) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除角色 "${role.roleName}" 吗？`,
      onOk: async () => {
        try {
          // 替换为实际API调用
          await fetch(`/api/roles/${role.id}`, { method: "DELETE" })
          message.success("删除成功")
          fetchRoles()
        } catch (error) {
          message.error("删除失败")
        }
      },
    })
  }

  const handleConfigPermissions = (role) => {
    setSelectedRole(role)
  }

  // 处理权限变更
  const onPermissionChange = (checkedKeys) => {
    if (selectedRole) {
      // 替换为实际API调用
      console.log("更新权限:", selectedRole.id, checkedKeys)
    }
  }

  // 表单提交
  const handleSubmit = async (values) => {
    try {
      // 替换为实际API调用
      await fetch("/api/roles", {
        method: "POST",
        body: JSON.stringify(values),
      })
      message.success("保存成功")
      setModalVisible(false)
      fetchRoles()
    } catch (error) {
      message.error("保存失败")
    }
  }

  useEffect(() => {
    fetchRoles()
  }, [])

  return (
    <>
      <PageHeaderWrapper title="权限管理" subtitle="角色权限配置" />
      <section className="G-main">
        <Row gutter={16}>
          <Col span={16}>
            <Card
              title="角色列表"
              extra={
                <Button type="primary" onClick={handleAddRole}>
                  新增角色
                </Button>
              }
            >
              <Table
                columns={columns}
                dataSource={roles}
                loading={loading}
                rowKey="id"
                pagination={{
                  defaultPageSize: 10,
                  showTotal: (total) => `共 ${total} 条记录`,
                }}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card
              title={`权限配置 ${
                selectedRole ? `- ${selectedRole.roleName}` : ""
              }`}
            >
              {selectedRole ? (
                <Tree
                  checkable
                  defaultExpandAll
                  treeData={permissionTreeData}
                  onCheck={onPermissionChange}
                />
              ) : (
                <div style={{ textAlign: "center", padding: "20px" }}>
                  请选择左侧角色进行权限配置
                </div>
              )}
            </Card>
          </Col>
        </Row>

        <Modal
          title={form.getFieldValue("id") ? "编辑角色" : "新增角色"}
          open={modalVisible}
          onOk={() => form.submit()}
          onCancel={() => setModalVisible(false)}
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              name="roleName"
              label="角色名称"
              rules={[{ required: true, message: "请输入角色名称" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="description" label="角色描述">
              <Input.TextArea />
            </Form.Item>
          </Form>
        </Modal>
      </section>
    </>
  )
}

export default Permission
